package com.lxq.springBoot.jedis;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


/**
 * 
 * @author lxq 2017年9月26日 上午10:57:06
 */
@WebFilter
public class SessionFilter implements Filter {
	private static final String host = "host";
	private static final String port = "port";
	private static final String seconds = "seconds";
	private final Logger logger = LoggerFactory.getLogger(SessionFilter.class);
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		String sid = null;
		if (httpRequest.getCookies() != null){
			for (Cookie cookie : httpRequest.getCookies()) {
				if (cookie.getName().equals("JSESSIONID")) {
					sid = cookie.getValue();
					break;
				}
			}
		}
		if (StringUtils.isEmpty(sid)) {
			Cookie cookie = new Cookie("JSESSIONID", httpRequest.getLocalAddr()+":"+httpRequest.getLocalPort()+":"+UUID.randomUUID().toString().replaceAll("-", ""));
			sid = cookie.getValue();
			httpResponse.addCookie(cookie);
		}
		logger.info("JSESSIONID:"+sid);
//		fc.doFilter(new HttpSessionWrapper(sid, httpRequest, httpResponse), httpResponse);
		fc.doFilter(httpRequest, httpResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logger.info("init filterConfig info");

	}

}
